package com.woniu.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.core.exception.account.AccountException;
import com.woniu.core.exception.account.AccountExceptionCode;
import com.woniu.core.exception.gym.GymException;
import com.woniu.core.exception.gym.GymExceptionCode;
import com.woniu.core.exception.product.ProductExceptionCode;
import com.woniu.core.exception.product.TCourseException;
import com.woniu.core.util.PageInfo;
import com.woniu.core.util.Result;
import com.woniu.product.client.AccountServerClient;
import com.woniu.product.client.GymServerClient;
import com.woniu.product.client.dto.CoachDto;
import com.woniu.product.client.dto.GymAccountDto;
import com.woniu.product.client.dto.GymBaseDto;
import com.woniu.product.dao.TCourseMapper;
import com.woniu.product.dto.TCourseDto;
import com.woniu.product.dto.TCourseQueryDto;
import com.woniu.product.model.TCourse;
import com.woniu.product.model.TCourseType;
import com.woniu.product.param.TCourseChangeParam;
import com.woniu.product.param.TCourseChangeStateParam;
import com.woniu.product.param.TCourseInsertParam;
import com.woniu.product.param.TCourseQueryParam;
import com.woniu.product.service.TCourseService;
import com.woniu.product.service.TCourseTypeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 吴彦祖
 * @since 2024年04月02日
 */
@Service
public class TCourseServiceImpl extends ServiceImpl<TCourseMapper, TCourse> implements TCourseService {
    @Resource
    private AccountServerClient accountServerClient;
    @Resource
    private GymServerClient gymServerClient;

    @Resource
    private TCourseTypeService tCourseTypeService;

    @Resource
    private TCourseMapper tCourseMapper;

    @Override
    public TCourse insert(TCourseInsertParam param) throws Exception {
        //得到场馆账户名称
        Result<GymAccountDto> GymAccountResult = accountServerClient.findGymAccountById(param.getGymId());
        if (GymAccountResult.getCode()!=200){
            throw new AccountException(AccountExceptionCode.NOT_FIND_THIS_GYM);
        }
        GymAccountDto gymAccountDto = GymAccountResult.getData();
        param.setCreateAdmin(gymAccountDto.getAccountName());

        //根据gymNum查询场馆是否存在
        Result<GymBaseDto> gymBaseResult = gymServerClient.findGymBaseByNum(param.getGymNum());
        if (gymBaseResult.getCode()!=200){
            throw new GymException(GymExceptionCode.GYM_NOT_EXIST);
        }
        GymBaseDto gymBaseDto = gymBaseResult.getData();
        //判断课程类别
        TCourseType type = tCourseTypeService.queryTypeById(param.getCourseTypeId());
        //判断课程形式
        if (param.getCourseVariety()!=1 && param.getCourseVariety()!=2){
            throw new TCourseException("不是团课也不是私课", ProductExceptionCode.TCOURSE_EXCEPTION_CODE.getCode());
        }

        TCourse tCourse = BeanUtil.toBean(param, TCourse.class);

        if (param.getCourseVariety()==2) {  //私课
            tCourse.setLimitNum(1);
            tCourse.setPlanState(0);
        }else {     //团课
            tCourse.setPlanState(1);
        }
        tCourse.setCourseState(1);
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String DateTime = now.format(formatter);
        tCourse.setCreateDate(DateTime);
        this.save(tCourse);

        return tCourse;
    }

    @Override
    public TCourse delete(Integer courseId) throws Exception {
        TCourse tCourse = this.getById(courseId);
        if (tCourse==null) {
            throw new TCourseException("课程信息不存在",ProductExceptionCode.TCOURSE_EXCEPTION_CODE.getCode());
        }
        //判断是否过有效期
        String createDate = tCourse.getCreateDate();
        LocalDateTime now = LocalDateTime.now();
        //得到创建日期
        LocalDateTime dateTime = LocalDateTime.parse(createDate, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        //追加三个月
        LocalDateTime threeMonths = dateTime.plusMonths(2);
        if (!now.isAfter(threeMonths)) {
            throw new TCourseException("课程未过有效期，不能删除",ProductExceptionCode.TCOURSE_EXCEPTION_CODE.getCode());
        }
        if (tCourse.getCourseState()==2) {
            throw new TCourseException("课程已上架，暂不能删除",ProductExceptionCode.TCOURSE_EXCEPTION_CODE.getCode());
        }
        if (tCourse.getCourseState()==0) {
            throw new TCourseException("课程已删除，请勿重复操作",ProductExceptionCode.TCOURSE_EXCEPTION_CODE.getCode());
        }
        tCourse.setCourseState(0);
        this.save(tCourse);
        return tCourse;
    }

    @Override
    public TCourse changeCourseById(TCourseChangeParam param) throws Exception {
        TCourse tCourse = this.getById(param.getCourseId());
        if (tCourse==null) {
            throw new TCourseException("课程信息不存在",ProductExceptionCode.TCOURSE_EXCEPTION_CODE.getCode());
        }
        TCourse tCourse1 = BeanUtil.toBean(param, TCourse.class);
        this.updateById(tCourse1);
        TCourse tCourse2 = this.getById(tCourse1);  //不建议查询2次数据库
        return tCourse2;
    }

    @Override
    public TCourseQueryDto queryCourseById(Integer courseId) throws Exception {
        TCourse tCourse = this.getById(courseId);
        if (tCourse==null) {
            throw new TCourseException("课程信息不存在",ProductExceptionCode.TCOURSE_EXCEPTION_CODE.getCode());
        }
        if(tCourse.getCourseState()==0){
            throw new TCourseException("课程状态异常",ProductExceptionCode.TCOURSE_EXCEPTION_CODE.getCode());
        }
        TCourseType type = tCourseTypeService.queryTypeById(tCourse.getCourseTypeId());
        TCourseQueryDto dto = BeanUtil.toBean(tCourse, TCourseQueryDto.class);
        if (dto.getCoachId()!=null) {
            CoachDto coachAccount = accountServerClient.getCoachAccountById(tCourse.getCoachId()).getData();
            dto.setCoachName(coachAccount.getCoachName());
        }
        dto.setCourseTypeName(type.getTypeName());
        return dto;
    }

    @Override
    public PageInfo<TCourseQueryDto> queryAll(TCourseQueryParam param) throws Exception {
        Page<TCourse> page = new Page<>(param.getPageNum() == null ? 1 : param.getPageNum(), param.getPageSize() == null ? 10 : param.getPageSize());
        QueryWrapper<TCourse> qw = new QueryWrapper<>();
        if (ObjectUtil.isNotEmpty(param.getGymNum())) {
            qw.eq("gym_num",param.getGymNum());
        }
        if (ObjectUtil.isNotEmpty(param.getCoachId())) {
            qw.eq("coach_id",param.getCoachId());
        }
        if (ObjectUtil.isNotEmpty(param.getCourseTypeId())) {
            qw.eq("course_type_id",param.getCourseTypeId());
        }
        if (ObjectUtil.isNotEmpty(param.getCourseVariety())) {
            qw.eq("course_variety",param.getCourseVariety());
        }
        if (ObjectUtil.isNotEmpty(param.getCourseState())) {
            qw.eq("course_state",param.getCourseState());
        }
        if (ObjectUtil.isNotEmpty(param.getPlanState())) {
            qw.eq("plan_state",param.getPlanState());
        }
        tCourseMapper.selectPage(page,qw);
        List<TCourse> records = page.getRecords();
        if (records==null ||records.size()<=0 || records.isEmpty() ){
            throw new TCourseException("课程信息不存在",ProductExceptionCode.TCOURSE_EXCEPTION_CODE.getCode());
        }
        List<TCourseQueryDto> dtos = BeanUtil.copyToList(records, TCourseQueryDto.class);
        for (TCourseQueryDto dto : dtos) {
            if (dto.getCoachId()!=null) {
                CoachDto coachAccount = accountServerClient.getCoachAccountById(dto.getCoachId()).getData();
                dto.setCoachName(coachAccount.getCoachName());
            }
            TCourseType type = tCourseTypeService.queryTypeById(dto.getCourseTypeId());
            dto.setCourseTypeName(type.getTypeName());
        }

        PageInfo info = BeanUtil.toBean(page, PageInfo.class);
        info.setList(dtos);
        info.setPages(page.getPages());

        return info;
    }

    @Override
    public TCourseDto changeStateById(TCourseChangeStateParam param) throws Exception {
        TCourse tCourse = this.getById(param.getCourseId());
        if (tCourse==null) {
            throw new TCourseException("课程信息不存在",ProductExceptionCode.TCOURSE_EXCEPTION_CODE.getCode());
        }
        if(tCourse.getCourseState()==param.getCourseState()){
            throw new TCourseException("课程状态相同无需更改",ProductExceptionCode.TCOURSE_EXCEPTION_CODE.getCode());
        }else if (param.getCourseState()==2){ //上架
            if (tCourse.getCourseState()!=1) {
                throw new TCourseException("课程状态不对",ProductExceptionCode.TCOURSE_EXCEPTION_CODE.getCode());
            }
        }else if(param.getCourseState()==3){ //下架
            if (tCourse.getCourseState()!=2) {
                throw new TCourseException("课程状态不对",ProductExceptionCode.TCOURSE_EXCEPTION_CODE.getCode());
            }
        }else if(param.getCourseState()==4) {//完结
            if (tCourse.getCourseState()!=3) {
                throw new TCourseException("课程状态不对",ProductExceptionCode.TCOURSE_EXCEPTION_CODE.getCode());
            }
        }else {
            throw new TCourseException("课程状态参数异常",ProductExceptionCode.TCOURSE_EXCEPTION_CODE.getCode());
        }

        tCourse.setCourseState(param.getCourseState());
        this.updateById(tCourse);

        TCourseDto tCourseDto = BeanUtil.toBean(tCourse, TCourseDto.class);
        if (tCourseDto.getCoachId()!=null) {
            CoachDto coachAccount = accountServerClient.getCoachAccountById(tCourse.getCoachId()).getData();
            tCourseDto.setCoachName(coachAccount.getCoachName());
        }
        TCourseType type = tCourseTypeService.queryTypeById(tCourseDto.getCourseTypeId());
        tCourseDto.setCourseTypeName(type.getTypeName());

        return tCourseDto;
    }

}
